package com.atguigu.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class MyLB implements LoadBalancer {

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    //这里业务处理逻辑是获取当前服务消费者访问（调用）注册中心上的服务的次数，次数要与预期值相同
    public final int getAndIncrement()
    {
        int current;
        int next;
        do
        {
            current = this.atomicInteger.get();
            next = current >= 2147483647 ? 0 : current + 1;
        } while(!this.atomicInteger.compareAndSet(current, next));
        System.out.println("*****第几次访问next: "+next);
        return next;
    }


    //通过服务消费者访问（调用）注册中心上的服务的次数与注册中心上的服务实例个数进行取余运算
    //根据取余运算结果来觉得轮询时给服务消费者调用服务提供者集群上的哪个服务实例
    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances)
    {
        int index = getAndIncrement() % serviceInstances.size();
        return serviceInstances.get(index);
    }


}
